package com.jie.pen;

import com.jie.common.Denlong;
import com.jie.dao.FileDao;
import com.jie.show.FileInfo;
import com.jie.service.FileService;
import com.jie.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


@RestController
@RequestMapping("/api/file")
public class FileController {
    @Autowired
    FileService FileService;

    @Autowired
    private FileService fileService;


    @GetMapping("/info")
    public Denlong getInfo(){
        List<FileInfo> res = fileService.getMyInfo();
        if (res != null){
            return new Denlong(1, "获取成功", res);
        }else {
            return new Denlong(0, "获取失败", null);
        }
    }

    /**
     * 文件上传接口
     *
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public Denlong upload(MultipartHttpServletRequest request) {
        Iterator<String> fileNames = request.getFileNames();
        List<FileInfo> fileList = new ArrayList<>();
        while (fileNames.hasNext()) {
            MultipartFile multipartFile = request.getFile(fileNames.next());
            FileInfo fileInfo = fileService.upload(multipartFile);
            fileList.add(fileInfo);
        }
        if (fileList.size() == 1) {
            return new Denlong(1, "上传成功", fileList.get(0));
        } else {
            return new Denlong(1, "上传成功", fileList);
        }
    }

    /**
     * 文件下载接口
     *
     * @param md5
     * @param response
     */
    @GetMapping("/{md5}")
    public void download(@PathVariable("md5") String md5, HttpServletResponse response) {
        fileService.download(response, md5);
    }

    @GetMapping("/music")
    public Denlong getMyMusic(@RequestParam("name") String name){
        List<FileInfo> list = fileService.getMyMusic(name);
        if (list!=null){
            return new Denlong(1, "成功", list);
        }else {
            return new Denlong(0, "失败", null);
        }
    }
}
